package com.example.haoge.study_expressage;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.activeandroid.query.Delete;
import com.activeandroid.util.Log;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;


public class MainActivity extends Activity implements View.OnClickListener, Serializable {
    private EditText edt_number;//快递单号
    private Button btn_search;//查询
    private Button btn_history;//查询历史
    private Button btn_exit;//退出
    private ImageView iv_scan, iv_recordIcon;//扫描和语音
    private ProgressDialog mprogressdialog;
    private Context context;
    private String urlString = "http://api.jisuapi.com/express/";//急速api
    private String keyType = "query";//快递查询
    private static final String APPKEY = "5077998df180fe80";
    private String expressNUM = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        android.util.Log.i("maty", "1233");
        context = this;
        initid();//初始化控件
        initclick();
        mprogressdialog = new ProgressDialog(context);
        mprogressdialog.setTitle("正在加载");
        // httpget();//获取数据 网络解析
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        expressNUM = intent.getStringExtra("number");
        expressNUM = expressNUM.trim();
        edt_number.setText(expressNUM);
    }

    private void initclick() {
        btn_search.setOnClickListener(this);
        btn_history.setOnClickListener(this);
        btn_exit.setOnClickListener(this);
        iv_recordIcon.setOnClickListener(this);
        iv_scan.setOnClickListener(this);
    }

    private void initid() {
        edt_number = (EditText) findViewById(R.id.edt_number);
        btn_search = (Button) findViewById(R.id.btn_search);
        btn_history = (Button) findViewById(R.id.btn_history);
        btn_exit = (Button) findViewById(R.id.btn_exit);
        ;
        iv_scan = (ImageView) findViewById(R.id.iv_saomiao);
        iv_recordIcon = (ImageView) findViewById(R.id.yuyin);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_search:
                mprogressdialog.show();
                expressNUM = edt_number.getText().toString().trim();
                httpget();
                break;
            case R.id.btn_history:
                Intent it = new Intent(context, HistoryActivity.class);
                startActivity(it);
                break;
            case R.id.btn_exit:
                finish();
                break;
            case R.id.yuyin:
                // 1.创建dialog对象
                RecognizerDialog dialog = new RecognizerDialog(context, null);
                // 2.加载语音识别监听
                dialog.setListener(mRecognizerDialogListener);
                // 3.显示dialog
                dialog.show();
                break;
            case R.id.iv_saomiao:
                Intent it1 = new Intent(context, CommonScanActivity.class);
                startActivity(it1);
                break;
        }

    }

    private void httpget() {
        //快递公司解析
        String typeUrL = urlString + "type" + "?appkey=" + APPKEY;
        StringRequest typeRequest = new StringRequest(typeUrL, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject object = new JSONObject(s);
                    //解析状态码
                    String status = object.getString("status");
                    if (status != null && status.equals("0")) {
                        JSONArray result = object.getJSONArray("result");
                        int size = result.length();
                        for (int i = 0; i < size; i++) {
                            JSONObject object2 = result.getJSONObject(i);
                            //方法1
//                            String type=object2.getString("type");
//                            String name=object2.getString("name");
                            //方法2
                            ExpressTypeDb typeDb = new ExpressTypeDb();
                            typeDb.expressType = object2.getString("type");
                            typeDb.expressName = object2.getString("name");
                            ifExitType(typeDb.expressType);//查重
                            android.util.Log.i("maty", typeDb.expressName);

                            typeDb.save();
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        BaseApp.GetQueue().add(typeRequest);
        String url = urlString + keyType + "?appkey=" + APPKEY + "&type=auto" + "&number=" + expressNUM;
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    mprogressdialog.dismiss();
                    JSONObject object = new JSONObject(s);
                    String status = object.getString("status");
                    //     Toast.makeText(context,s,Toast.LENGTH_SHORT).show();
                    //状态不为空 且为字符串0 表示单号正确
                    if (status != null && status.equals("0")) {
                        JSONObject result = object.getJSONObject("result");
                        ExpressDb db = new ExpressDb();
                        db.expressNum = expressNUM;
                        db.resultJson = result.toString();
                        ifExitNum(expressNUM);//查重
                        db.save();

                        Intent it = new Intent(context, TrackActivity.class);
                        it.putExtra("number", expressNUM);
                        startActivity(it);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
//添加request到网络解析序列栈
        BaseApp.GetQueue().add(request);


    }

    private void ifExitNum(String expressNUM) {
        //查重
        new Delete().from(ExpressDb.class).where("number=?", expressNUM).executeSingle();
    }

    private void ifExitType(String typeString) {
        //查重
        new Delete().from(ExpressTypeDb.class).where("type=?", typeString).executeSingle();
    }

    // 监听语音输入的监听器
    RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {
            // 打印结果 当isLast为true时,说明结果结束
            Log.i("huark", "讯飞语音");
            String expressNum = Contast.parseIatResult(results
                    .getResultString());
            // 拼接
            if (!isLast) {
                edt_number.append(expressNum);
            }
        }

        public void onError(SpeechError error) {
            // 出错
        }
    };
}
